<?php

namespace Api\Controller;

use Think\Controller;

class ShopController extends CommonController
{
    private $eatName = array();

    public function index()
    {
        if (isset($_GET['pageNum'])) {
            $page = I('pageNum');
            $page = (int)$page * 10;
        } else {
            $page = 0;
        }

        $map = array();

        // 需要判断分类是一级分类还是二级分类
       if(intval(I('cid'))>0) {
           //$map['cid'] = $_GET['cid'];
            $cid = I('cid');
            $cate = M("Cate")->where("id=$cid")->find();

        //$map['join_end_time'] = array('<=',date('Y-m-d H:i:s',time()));
            if ($cate['pid']) {
                $map['cid'] = I('cid');
            } else {
                // 是一级分类的时候
                $map['_string'] = "cid in (select id from tp_cate where pid = $cid)";
                //$map['cid'] = 0;
            }
        }
        if(I('aid') !=""){
            $where['id'] = I('aid');
            if($where['id'] != 0){
                //不是选择全辖区
                $city = M('city')->where($where)->find();
            }else{
                //选择全辖区
                $map2['wid'] = session('wid');
                $wechat = M("Wechat")->where($map2)->find();
                $where2['city_code'] = $wechat['city'];
                $city = M("City")->where($where2)->find();
            }
            $map['county_name | site_name'] = ['like',"%".$city['city_name']."%"];
        }

        if ($_GET['type']) {
            $map['type'] = $_GET['type'];
        }
        $map['wid'] = session('wid');
        $map['status'] = 1;
        //$list = M("Shop")->where($map)->order("last_time desc")->select();
        $list = M("shop")->where($map)
                          ->where(['join_end_time' => ['gt', date('Y-m-d H:i:s', time())]])
                          ->order("last_time desc")
                          ->limit(0, $page)
                          ->select();
        //筛选美食
        $eatArr = $this->eatCates();
        foreach ($list as $key => $value) {
            if (in_array($value['cate'] , $eatArr)) {
                $list[$key]['is_eat'] = 1;
            } else {
                $list[$key]['is_eat'] = 0;
            }
        }
        foreach ($list as $key => $value) {
            $list[$key]['type'] = trim($value['type']);
            //商户距离计算
            if (I('la') != 'undefined' && I('lo') != 'undefined') {
                if ($value['latitude'] && $value['longitude']) {
                    $earthRadius = 6367000;
                    $lat1 = (float) I('la');//纬度
                    $lng1 = (float) I('lo');//经度
                    $lat2 = (float) $value['latitude'];
                    $lng2 = (float) $value['longitude'];
                    $lat1=($lat1* pi()) / 180;
                    $lng1=($lng1* pi()) / 180;
                    $lat2=($lat2* pi()) / 180;
                    $lng2=($lng2* pi()) / 180;
                    $calcLongitude = $lng2-$lng1;
                    $calcLatitude = $lat2-$lat1;
                    $stepOne = pow(sin($calcLatitude/2),2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude/2),2);
                    $stepTwo = 2* asin(min(1, sqrt($stepOne)));
                    $distance = round($earthRadius*$stepTwo);
                    if ($distance < 1000) {
                        $list[$key]['r_distance'] = $distance.'米';
                    } else {
                        $distance = $distance / 1000;
                        $list[$key]['r_distance'] = round($distance, 2).'公里';
                    }
                } else {
                    $list[$key]['r_distance'] = '';
                }
            } else {
                $list[$key]['r_distance'] = '';
            }
        }
        $this->ajaxReturn($list);
        
        foreach ($list as $k => $v) {
            $eq['shop_id'] = $v['shop_id'];
            $eq['is_pin'] = 1;
            $eq['status'] = 1;
            $list[$k]['has_pin'] = M("Goods")->where($eq)->find();

            $eq1['shop_id'] = $v['shop_id'];
            $eq1['is_pin'] = 0;
            $eq1['is_kan'] = 1;
            $eq1['status'] = 1;
            $list[$k]['has_kan'] = M("Goods")->where($eq1)->find();

            $eq2['shop_id'] = $v['shop_id'];
            $eq2['is_qiang'] = 1;
            $eq2['status'] = 1;
            $list[$k]['has_qiang'] = M("Goods")->where($eq2)->find();

            $eq3['shop_id'] = $v['shop_id'];
            $eq3['status'] = 1;
            // $eq3['is_qiang'] = 1;
            $list[$k]['has_coupon'] = M("Coupon")->where($eq3)->find();
        }
        $this->ajaxReturn($list);
    }

    public function follow()
    {
        $model = M('ShopFollow');

        $eq['shop_id'] = $_POST['shop_id'];
        $eq['openid'] = $_POST['openid'];
        if ($model->where($eq)->find()) {
            if ($model->where($eq)->delete()) {
                $arr = array("err_code" => 0, "err_msg" => "-1");
                $this->ajaxReturn($arr);
            } else {
                $arr = array("err_code" => 400, "err_msg" => "网络忙！");
                $this->ajaxReturn($arr);
            }
        } else {
            $eq['create_time'] = date("Y-m-d H:i:s");
            if ($model->add($eq)) {
                $arr = array("err_code" => 0, "err_msg" => "1");
                $this->ajaxReturn($arr);
            } else {
                $arr = array("err_code" => 400, "err_msg" => "网络忙！");
                $this->ajaxReturn($arr);
            }
        }
    }

    public function topic()
    {
        $map = array();
        $map['cid'] = $_GET['cid'];
        $map['wid'] = session('wid');
        // $map['status'] = 1;
        $list = M("Topic")->where($map)->order("last_time desc")->select();
        $this->ajaxReturn($list);
    }

    public function haveShop()
    {
        $map['wid'] = session('wid');
        $map['openid'] = $_POST['openid'];
        $map['status'] = 1;
        if (M("Shop")->where($map)->find()) {
            $arr = array("is_have" => true, "title" => '商户中心', "url" => "/pages/mine/shop/shop");
        } else {
            $arr = array("is_have" => false, "title" => '我要开店', "url" => "/pages/shop/add");
        }
        $this->ajaxReturn($arr);
    }

    public function item()
    {
        //$map['wid'] = session('wid');
        $map['shop_id'] = $_GET['shop_id'];
        $info = M("Shop")->where($map)->find();
        $info['pics'] = explode(",", $info['pics']);
        $info['shop_banner'] = explode(",", $info['shop_banner']);

        $eq['shop_id'] = I("shop_id");
        $eq['openid'] = I("openid");
        $info['is_follow'] = M("ShopFollow")->where($eq)->getField('id');
        $this->ajaxReturn($info);
    }

    public function renling()
    {
        $eq['wid'] = session('wid');
        $eq['openid'] = $_POST['openid'];
        $eq['is_pay'] = 1;
        if (M("Shop")->where($eq)->find()) {
            $arr = array("err_code" => 400, "err_msg" => "您已入驻本平台！");
            $this->ajaxReturn($arr);
        }

        $_POST['wid'] = session('wid');
        foreach ($_POST as $key => $value) {
            if (!is_numeric($value) && empty($value)) {
                $arr = array("err_code" => 400, "err_msg" => "请填写全部信息！");
                $this->ajaxReturn($arr);
            }
        }
        if (M("Renling")->add($_POST)) {
            $arr = array("err_code" => 0, "err_msg" => "申请提交成功！");
            $this->ajaxReturn($arr);
        } else {
            $arr = array("err_code" => 400, "err_msg" => "网络忙，请稍后再试！");
            $this->ajaxReturn($arr);
        }
    }

    public function add()
    {
        // $arr = array("err_code"=>400, "err_msg"=>"平台升级中，暂停入驻！");
        // $this->ajaxReturn($arr);

        $eq['wid'] = session('wid');
        $eq['openid'] = $_POST['openid'];
        $eq['is_pay'] = 1;
        if (M("Shop")->where($eq)->find()) {
            $arr = array("err_code" => 400, "err_msg" => "您已入驻本平台！");
            $this->ajaxReturn($arr);
        }
        foreach ($_POST as $key => $value) {
            if (!is_numeric($value) && empty($value)) {
                $arr = array("err_code" => 400, "err_msg" => "请填写全部信息！");
                $this->ajaxReturn($arr);
            }
        }
        if ($_POST['sub_cate'] != '全部') {
            $_POST['cate'] = $_POST['sub_cate'];
        }
        $where['title'] = $_POST['cate'];
        $where['wid'] = session('wid');
        $where['type'] = 'shop';
        $_POST['cid'] = M("Cate")->where($where)->getField("id");
        // $days = M('Join')->where(array('id'=>$_POST['join_id']))->getField('days');
        // $_POST['join_end_time'] = date('Y-m-d H:i:s',strtotime('+'.$days.' day'));
        $_POST['wid'] = session('wid');
        $_POST['create_time'] = date("Y-m-d H:i:s");
        $_POST['status'] = 0;

        if ($shop_id = M("Shop")->add($_POST)) {
            $this->getShopOrder($shop_id);

            $map['shop_id'] = $shop_id;
            $data['is_pay'] = 1;
            M("Shop")->where($map)->save($data);
            $arr = array("err_code" => 0, "err_msg" => "发布成功！");
            $this->ajaxReturn($arr);
        } else {
            $arr = array("err_code" => 400, "err_msg" => "网络忙，请稍后再试！");
            $this->ajaxReturn($arr);
        }

    }

    public function getAddForm()
    {
        $map['wid'] = session('wid');
        $wechat = M("Wechat")->where($map)->find();

        $map['id'] = $_GET['id'];

        $top_input = array('type' => 'top');

        $where['city_code'] = $wechat['city'];
        $city = M("City")->where($where)->find();
        $where1['pid'] = $city['id'];
        $site_arr2 = M("City")->where($where1)->getField("city_name", true);
        if ($wechat['city'] == 0) {
            $site_arr1 = array("全国");
        } else {
            $site_arr1 = array($city["city_name"]);
            if (!$site_arr2) {
                $site_arr2 = array("全辖区");
            }
        }
        $site_input = array(
            'type' => 'picker2',
            'title' => '所在区域',
            'name' => array('county_name', 'site_name'),
            'range' => array($site_arr1, $site_arr2),
            'value' => array(0, 0)
        );

        $cate_map['wid'] = session('wid');
        $cate_map['type'] = 'shop';
        $cate_map['pid'] = 0;

        $cates = M("Cate")->where($cate_map)->field("id as cid,title")->select();
        // dump($cates);
        foreach ($cates as $k => $v) {
            $cate_map['pid'] = $v['cid'];
            $cate_range[] = $v['title'];
            $sub_cates = M("Cate")->where($cate_map)->field("id as cid,title")->select();
            if ($sub_cates) {
                $cates[$k]['sub_cates'] = $sub_cates;
                foreach ($sub_cates as $key => $value) {
                    $cates[$k]['sub_range'][] = $value['title'];
                }
            } else {
                $cates[$k]['sub_cates'][] = array('cid' => 0, 'title' => '全部');
                $cates[$k]['sub_range'][] = '全部';
            }
        }
        $cate_input = array(
            'type' => 'picker3',
            'title' => '店铺分类',
            'cates' => $cates,
            'name' => array('cate', 'sub_cate'),
            'range' => array($cate_range, $cates[0]['sub_range']),
            'value' => array(0, 0),
        );
        $res['add_url'] = "https://www.58zltc.com/api.php/Shop/add";
        //$res['add_url'] = "https://58zltc.bbrfx.cn/api.php/Shop/add";
        $res['index_url'] = "/pages/shop/shop";

        $form[] = array('type' => 'text', 'title' => '店铺名称', 'name' => 'name');
        $form[] = $cate_input;
        $form[] = $site_input;
        $form[] = array('type' => 'text', 'title' => '店铺地址', 'name' => 'address');
        $form[] = array('type' => 'number', 'title' => '人均消费', 'name' => 'person_money');
        $form[] = array('type' => 'time2', 'title' => '营业时间', 'name1' => 'start_time', 'value1' => '09:00', 'name2' => 'end_time', 'value2' => '21:00');
        $form[] = array('type' => 'top');
        $form[] = array('type' => 'pic', 'title' => '店铺Logo', 'name' => 'logo_url', 'num' => 1, 'pics' => array());
        $form[] = array('type' => 'top');
        $form[] = array('type' => 'pic', 'title' => '店铺图片', 'name' => 'pics', 'num' => 2, 'pics' => array());
        $form[] = array('type' => 'top');
        $form[] = array('type' => 'textarea', 'title' => '详细介绍', 'name' => 'content');
        $form[] = array('type' => 'top');
        $form[] = array('type' => 'text', 'title' => '联系人', 'name' => 'username');
        $form[] = array('type' => 'text', 'title' => '联系电话', 'name' => 'tel');
        $form[] = array('type' => 'top');
        // $form[] = array('type'=>'price', 'title'=>'平台入驻费', 'price'=>$wechat['shop_fee'], 'unit'=>'年');

        $eq['wid'] = session('wid');
        // $top_arr = array("免费体验");
        $top_arr = M("Join")->where($eq)->getField('title',true);
        $id_arr = M("Join")->where($eq)->getField('id',true);
        // if($top_arr2){
        //     $top_arr = array_merge($top_arr,$top_arr2);
        // }
        $form[] = array('type' => 'picker1', 'title' => '平台入驻费', 'name' => 'join_fee'
        , 'range' => $top_arr
        , 'id'=> $id_arr
        , 'value' => 0);
        $res['form'] = $form;
        $this->ajaxReturn($res);
    }

    public function getRenlingForm()
    {
        $map['wid'] = session('wid');
        $wechat = M("Wechat")->where($map)->find();

        $map['id'] = $_GET['id'];

        $top_input = array('type' => 'top');

        $form[] = array('type' => 'text', 'title' => '联系人', 'name' => 'username');
        $form[] = array('type' => 'text', 'title' => '联系电话', 'name' => 'tel');
        $form[] = array('type' => 'top');
        // $form[] = array('type'=>'price', 'title'=>'平台入驻费', 'price'=>$wechat['shop_fee'], 'unit'=>'年');
        $res['add_url'] = "https://www.58zltc.com/api.php/Shop/renling";
        $res['index_url'] = "/pages/shop/shop";
        // $eq['wid'] = session('wid');
        // // $top_arr = array("免费体验");
        // $top_arr = M("Join")->where($eq)->getField('title',true);
        // // if($top_arr2){
        // //     $top_arr = array_merge($top_arr,$top_arr2);
        // // }
        // $form[] = array('type'=>'picker1', 'title'=>'平台入驻费', 'name'=>'join_fee' 
        //         ,'range'=>$top_arr
        //         , 'value'=>0);
        $res['form'] = $form;
        $this->ajaxReturn($res);
    }

    //
    public function shopInfo () {
        $shopId = I('shop_id');
        $shopInfo = M('shop')->where(['shop_id' => $shopId])->find();
        $this->ajaxReturn($shopInfo);
    }

    //
    public function getJoinInfo () {

        $joinInfo = M('join')->where(['wid' => session('wid')])->select();
        $this->ajaxReturn($joinInfo);
    }
    public function renew (){
        $wid= session('wid');
        $join_info = M('Join')->where(array('id'=>$_POST['join_id']))->find();
        $shop_info = M('Shop')->where(array('shop_id'=>$_POST['shop_id']))->find();
        if(empty($join_info) || empty($shop_info)){
            $arr = array("err_code" => 400, "err_msg" => "参数错误！");
            $this->ajaxReturn($arr);
        }
        $this->renewShopOrder($_POST['shop_id']);
    }

    //
    public function eatCates () {
        $wid= session('wid');
        $this->eatName[] = '美食';
        $eat = M('cate')->where(['title' => '美食', 'pid' => '0', 'wid' => $wid])->find();
        $this->recursion($eat['id']);
        //$this->ajaxReturn($this->eatName);
        return $this->eatName;
    }
    public function recursion ($id) {
        $list = M('cate')->where(['pid' => $id])->select();
        if ($list) {
            foreach ($list as $key => $value) {
                $this->eatName[] = $value['title'];
                if ($value['id']) {
                    $this->recursion($value['id']);
                }
            }
        }
    }
}